package com.diaohw.platform.utility.ws;

import cn.hutool.core.collection.CollectionUtil;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.time.LocalDateTime;
import java.util.List;

import static com.diaohw.platform.common.constant.RequestConstant.AUTHORIZATION;


/**
 * @author 刁海文
 * @Remark websocket 配置
 * @since 2022/4/11 15:29
 */
@EnableWebSocket
@Configuration
public class WebsocketConfig extends ServerEndpointConfig.Configurator {
    public final static String Auth = "Sec-WebSocket-Protocol";

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    public final static String ONLINE_TIME = "OnlineTime";


    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        List<String> list = request.getHeaders().get(Auth);
        response.getHeaders().put(Auth, list);
        sec.getUserProperties().put(ONLINE_TIME, LocalDateTime.now());
        if (CollectionUtil.isNotEmpty(list)) {
            sec.getUserProperties().put(AUTHORIZATION, list.get(0));
        }
        super.modifyHandshake(sec, request, response);
    }


}

